import React, { Component } from "react";
import {
    StyleSheet,
    Text,
    View,
    ScrollView,
    Image,
    Animated,
    DeviceEventEmitter,
    Platform,
    NativeAppEventEmitter,
    TouchableOpacity,
    Modal,
    Button,
    NetInfo,
    Linking,
    NativeModules,
    BackHandler,
    ProgressBarAndroid,
    AppState
} from "react-native";
import styles from "./indexStyle";
import api from "../../services/api";
import Touch from "../global/Touch";
import RNFS from "react-native-fs";
import ToastTip from '../global/ToastTip';


class versionUpdate extends Component {
    constructor(props) {
        super(props);
        // console.log(this.props.lastVersionInfo,'sadasdasversioninfo')
        this.state = {
            isSetting: false,
            progressNum: 0,
            isMust: false,
            isDownloading: false,
            isError: false,
            currentAppState:AppState.currentState,
            bLength:0
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({isMust:nextProps.lastVersionInfo.forceUpdate});
    }

    componentDidMount() {
        
    }

    //打开系统的设置页面
    openSettings() {
        NativeModules.OpenSettings.openAndroidSystemPage(
            "android.settings.WIFI_SETTINGS",
            data => {
                console.log("call back data", data);
            }
        );
    }

    //设置Wi-Fi时监听用户页面的变化
    _handleAppStateChange = (nextAppState) => {
        if (this.state.currentAppState.match(/inactive|background/) && nextAppState === 'active') {
          console.log('App has come to the foreground!')
          setTimeout(() => {
          NetInfo.fetch().done(status => {
                if (status === "WIFI") {
                    this.refs.toast.show('已切换至WIFI网络,即将开始下载', 100, ()=>{
                        AppState.removeEventListener('change', this._handleAppStateChange);
                        this.setState({isDownloading:true},this.download);
                    });
                } 
            });
          }, 100);
        }
        this.setState({currentAppState: nextAppState});
    }

    //下载失败的弹窗内容
    renderDownloadFail = () => {
        return (
            <View
                style={{
                    backgroundColor: "#0005",
                    flex: 1,
                    justifyContent: "center",
                    alignItems: "center"
                }}
            >
                <View
                    style={{
                        width: 290,
                        height: 217.5,
                        backgroundColor: "#fff",
                        justifyContent: "space-between",
                        borderColor: "#ddd",
                        borderWidth: StyleSheet.hairlineWidth
                    }}
                >
                    <View
                        style={{
                            flexDirection: "row",
                            borderBottomColor: "#ddd",
                            borderBottomWidth: StyleSheet.hairlineWidth
                        }}
                    >
                        <Text
                            style={[{
                                height: 44,
                                color: "#565656",
                                fontSize: 15,
                                flex: 1,
                                textAlign: "center",
                                textAlignVertical: "center",
                            },this.state.isMust?{}:{paddingLeft:30}]}
                        >
                            温馨提示
                        </Text>
                        {!this.state.isMust ? (
                            <TouchableOpacity
                                activeOpacity={0.8}
                                style={{
                                    alignSelf: "center",
                                    paddingRight: 15,
                                    position:"absolute",
                                    right:0, 
                                }}
                                onPress={this.props.closeModal}
                            >
                                <Image
                                    source={require("../../../img/dialog_close.png")}
                                    style={{
                                        width: 15,
                                        height: 15,
                                    }}
                                />
                            </TouchableOpacity>
                        ) : null}
                    </View>
                    <Text
                        style={{
                            color: "#565656",
                            padding: 15,
                            fontSize: 15,
                            alignSelf:'center',
                            textAlign:'center'
                        }}
                    >
                        网络异常，新版本安装包下载失败
                    </Text>
                    <View
                        style={{
                            flexDirection: "row",
                            height: 44
                        }}
                    >
                        <Text
                            style={{
                                flex: 1,
                                color: "#EA5404",
                                fontSize: 15,
                                borderColor: "#ddd",
                                borderWidth: StyleSheet.hairlineWidth,
                                textAlign: "center",
                                textAlignVertical: "center"
                            }}
                            onPress={() => {
                                this.setState({isError:false},this.download)
                            }}
                        >
                            重新下载
                        </Text>
                    </View>
                </View>
            </View>
        );
    };
    //提示用户设置Wi-Fi
    renderSettingWifi = () => {
        let {lastVersionInfo} = this.props;
        return (
            <View
                style={{
                    backgroundColor: "#0005",
                    flex: 1,
                    justifyContent: "center",
                    alignItems: "center"
                }}
            >
                <View
                    style={{
                        width: 290,
                        height: 217.5,
                        backgroundColor: "#fff",
                        justifyContent: "space-between",
                        borderColor: "#ddd",
                        borderWidth: StyleSheet.hairlineWidth
                    }}
                >
                    <View
                        style={{
                            flexDirection: "row",
                            borderBottomColor: "#ddd",
                            borderBottomWidth: StyleSheet.hairlineWidth,
                            alignItems:'center'
                        }}
                    >
                        <Text
                            style={{
                                height: 44,
                                color: "#565656",
                                fontSize: 15,
                                flex: 1,
                                textAlign: "center",
                                textAlignVertical: "center",
                                // paddingLeft:30                                
                            }}
                        >
                            温馨提示
                        </Text>
                        {!this.state.isMust ? (
                            <TouchableOpacity
                                activeOpacity={0.8}
                                style={{
                                    alignSelf: "center",
                                    paddingRight: 15,
                                    position:"absolute",
                                    right:0,                                    
                                }}
                                onPress={this.props.closeModal}
                            >
                                <Image
                                    source={require("../../../img/dialog_close.png")}
                                    style={{
                                        width: 15,
                                        height: 15,
                                    }}
                                />
                            </TouchableOpacity>
                        ) : null}
                    </View>
                    <Text
                        style={{
                            color: "#565656",
                            padding: 15,
                            fontSize: 15
                        }}
                    >
                        正在使用非WIFI网络，下载将产生流量费用。<Text style={{color:'#ED5600'}}>流量：约{Number(lastVersionInfo.apk.fileSize/(1024*1024)).toFixed(1)}M</Text>
                    </Text>
                    <View
                        style={{
                            flexDirection: "row",
                            height: 44
                        }}
                    >
                        <Text
                            onPress={() => {
                                AppState.addEventListener('change', this._handleAppStateChange);
                                this.openSettings();
                            }}
                            style={{
                                flex: 1,
                                color: "#565656",
                                fontSize: 15,
                                borderColor: "#ddd",
                                borderWidth: StyleSheet.hairlineWidth,
                                textAlign: "center",
                                textAlignVertical: "center"
                            }}
                        >
                            设置WIFI
                        </Text>
                        <Text
                            style={{
                                flex: 1,
                                color: "#EA5404",
                                fontSize: 15,
                                borderColor: "#ddd",
                                borderWidth: StyleSheet.hairlineWidth,
                                textAlign: "center",
                                textAlignVertical: "center"
                            }}
                            onPress={() => {
                                this.setState({ isDownloading: true },this.download);
                            }}
                        >
                            继续下载
                        </Text>
                    </View>
                </View>
                <ToastTip ref="toast" offsetY={160}/>                
            </View>
        );
    };
    //发现更新弹窗页面
    renderFindUpdate = () => {
        let { showModal, closeModal, lastVersionInfo } = this.props;
        let styless = {alignSelf:'center'};
        return (
            <View
                style={{
                    backgroundColor: "#0005",
                    flex: 1,
                    justifyContent: "center",
                    alignItems: "center"
                }}
            >
                <View>
                {!this.state.isMust ? (
                    <TouchableOpacity
                        activeOpacity={0.8}
                        style={{
                            alignSelf:'flex-end',
                        }}
                        onPress={closeModal}
                    >
                        {/* <Text>sadasdasd</Text> */}
                        <Image
                            source={require("../../../img/v_close.png")}
                            style={{
                                width: 30,
                                height: 30,
                                marginBottom: 10
                            }}
                        />
                    </TouchableOpacity>
                    ) : null}
                <View
                    style={{
                        width: 300,
                        height: 375,
                        backgroundColor: "#fff",
                        justifyContent: "space-between",
                        borderColor: "#ddd",
                        borderWidth: StyleSheet.hairlineWidth,
                        position:'relative',
                        overflow:'visible'
                    }}
                >   
                    <View>
                        <Image
                            source={require("../../../img/phone_bg.png")}
                            style={{
                                marginTop: 25,
                                width: 123.5,
                                height: 106.5,
                                alignSelf: "center"
                            }}
                        />
                        <Text
                            style={{
                                color: "#565656",
                                alignSelf: "center",
                                fontSize: 18,
                                marginTop: 12
                            }}
                        >
                            发现新版本
                        </Text>
                        <Text
                            style={{
                                color: "#fff",
                                height: 21,
                                marginTop: 5.5,
                                borderRadius: 10.5,
                                backgroundColor: "#EA5404",
                                alignSelf: "center",
                                textAlign: "center",
                                paddingHorizontal:10
                            }}
                        >
                            V{lastVersionInfo.version}
                        </Text>
                    </View>
                    <View
                        style={{
                            paddingHorizontal:35
                        }}
                    >
                        <Text
                            style={[{
                                color: "#7b7b7b",
                                fontSize: 13,
                                marginBottom:5,
                            },this.b?styless:{}]}
                        >
                            更新说明:
                        </Text>
                        <ScrollView
                            horizontal={false}
                            showsVerticalScrollIndicator={true}
                            style={{
                                height: 92.5,
                                flexGrow: 0
                            }}
                        >
                            <View
                                style={{
                                    display:'flex',
                                }}
                            >
                                {this.renderMarkList(lastVersionInfo.remark||'')}
                            </View>
                        </ScrollView>
                    </View>
                    <View
                        style={{
                            flexDirection: "row",
                            height: 44
                        }}
                    >
                        {!this.state.isMust ? (
                            <Text
                                onPress={closeModal}
                                style={{
                                    flex: 1,
                                    color: "#565656",
                                    fontSize: 15,
                                    borderColor: "#ddd",
                                    borderWidth: StyleSheet.hairlineWidth,
                                    textAlign: "center",
                                    textAlignVertical: "center"
                                }}
                            >
                                暂不更新
                            </Text>
                        ) : null}
                        <Text
                            style={{
                                flex: 1,
                                color: "#EA5404",
                                fontSize: 15,
                                borderColor: "#ddd",
                                borderWidth: StyleSheet.hairlineWidth,
                                textAlign: "center",
                                textAlignVertical: "center"
                            }}
                            onPress={() => {
                                NetInfo.fetch().done(status => {
                                    if (status !== "WIFI") {
                                        this.setState({
                                            //网络不是wifi时显示弹窗让用户设置wifi
                                            isSetting: true
                                        });
                                    } else {
                                        this.setState({
                                            //网络是wifi时直接开始下载
                                            isDownloading: true
                                        },this.download);
                                        //设置下载 isDownloading
                                        // this.setState({
                                        //     //网络不是wifi时显示弹窗让用户设置wifi
                                        //     isSetting: true
                                        // });
                                    }
                                });
                            }}
                        >
                            {this.state.isMust?'有新版本请立即更新':'立即更新'}
                        </Text>
                    </View>
                </View>
                </View>
                
            </View>
        );
    };

    renderMarkList = (c) => {
        // c = c.replace(/<p>/g, "");
        // c = c.replace(/<br>/g, "");
        let b = c = c.replace(/&nbsp;/g, "");
        // c = c.replace(/<\/p>/g, "");


        // c = c.replace(/&nbsp;/g, "");
            // c = c.replace(/<br>/g, "");
        b = b.replace(/&lt;/g,"<");
        b = b.replace(/&gt;/g,'>');
        // c = c.replace(/<[^>]*>/g,"");
        b = b.split(/<[^>]*>/g);
        b = b.filter((item) => {
            if(item){return item}
        })
        if (b.length==1) {
            this.b = 1;
        }
        return b.map((item, index) => {
            if(b.length==1){
                return <Text style={{color: "#7b7b7b",fontSize: 13,alignSelf:'center'}} key={index}>{item}</Text>
            }else{
                return <Text style={{color: "#7b7b7b",fontSize: 13}} key={index}>{item}</Text>
            }
        })
    }

    //下载进度页面
    renderProgress = () => {
        let { progressNum } = this.state;
        return (
            <View
                style={{
                    backgroundColor: "#0005",
                    flex: 1,
                    justifyContent: "center",
                    alignItems: "center"
                }}
            >
                <View
                    style={{
                        width: 260,
                        height: 108.5,
                        backgroundColor: "#fff",
                        justifyContent: "space-around",
                        borderColor: "#ddd",
                        borderWidth: StyleSheet.hairlineWidth
                    }}
                >
                    <Text
                        style={{
                            paddingTop: 20,
                            color: "#565656",
                            fontSize: 15,
                            flex: 1,
                            textAlign: "center",
                            textAlignVertical: "center",
                            paddingBottom: 10
                        }}
                    >
                        正在下载新版本
                    </Text>
                    <Myprogress progress={progressNum} />
                    <Text
                        style={{
                            color: "#565656",
                            // padding: 15,
                            paddingBottom: 10,
                            fontSize: 15,
                            textAlign: "center",
                            textAlignVertical: "center"
                        }}
                    >
                        {parseInt(progressNum * 100) + "%"}
                    </Text>
                </View>
            </View>
        );
    };

    download = () => {
        const DownloadURL =this.props.lastVersionInfo.apk.url;
        const options = {
            fromUrl: DownloadURL,
            toFile: RNFS.DocumentDirectoryPath + "/管家来了.apk",
            background: true,
            begin: res => {
                console.log("begin", res);
                console.log(
                    "contentLength:",
                    res.contentLength / 1024 / 1024,
                    "M"
                );
            },
            progress: res => {
                let pro = res.bytesWritten / res.contentLength;
                console.log(pro);
                this.setState({
                    progressNum: pro
                });
            }
        };

        try {
            const ret = RNFS.downloadFile(options);
            ret.promise
                .then(res => {
                    this.setState({ progressNum: 1 }, () => {
                        if (!this.state.isMust) {
                            this.setState({isDownloading:false,isSetting:false},() => {
                                this.props.closeModal()
                            });                 
                        } else {
                            this.setState({isDownloading:false,isSetting:false});
                        }
                        
                        NativeModules.InstallApk.install(
                            `${RNFS.DocumentDirectoryPath}/管家来了.apk`
                        );
                    });
                })
                .catch(err => {
                    this.setState({ isError: true });
                });
        } catch (e) {
            this.setState({ isError: true });
        }
    };

    // listerBack() {
    //     return true;
    // }

    render() {
        let { showModal, closeModal } = this.props;
        let { isSetting, isMust, isDownloading, isError } = this.state;

        return (
            <Modal
                // style={styles.scrollContent}
                animationType={"fade"}
                transparent={true}
                visible={showModal}
                onRequestClose={() => {
                    // closeModal();
                }}
            >
                {/* {this.renderProgress()} */}
                {!isSetting
                    ? !isDownloading
                        ? this.renderFindUpdate()
                        : !isError
                            ? this.renderProgress()
                            : this.renderDownloadFail()
                    : !isDownloading
                        ? this.renderSettingWifi()
                        : !isError
                            ? this.renderProgress()
                            : this.renderDownloadFail()}
            </Modal>
        );
    }
}

// 进度条组件
class Myprogress extends Component {
    render() {
        let { progress } = this.props;
        return (
            <ProgressBarAndroid
                style={{ marginHorizontal: 50, borderRadius: 2 }}
                styleAttr="Horizontal"
                progress={progress}
                color="#EA5404"
                indeterminate={false}
            />
        );
    }
}

export default versionUpdate;
